<template>
  <div>
    <div style="display: flex; width: 100%; text-align: right">
      <el-button type="primary" @click="add">添加用户</el-button>
    </div>
    <el-table :data="list" stripe style="width: 100%">
      <el-table-column prop="username" label="用户名" min-width="180"></el-table-column>
      <el-table-column prop="createdTime" label="注册时间" min-width="180"></el-table-column>
      <el-table-column label="折扣线路" min-width="180">
        <template slot-scope="scope">
          <a href="javascript:;" @click="showDiscountDialog(scope.row)">{{ scope.row.discountCount }}</a>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="danger" size="small" @click="del(scope.index, scope.row)">删除</el-button>
            <el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="this.page.total"
        :current-page="this.page.page"
        :page-size="this.page.size">
    </el-pagination>

    <el-dialog :title="dialog.title" :visible.sync="dialog.show" width="520px">
      <div>
        <el-form ref="form" :model="info" label-width="120px">
          <el-form-item label="用户名" prop="username" required>
            <el-input v-model="info.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" :required="!info.id">
            <el-input v-model="info.password" type="password"
                      :placeholder="info.id ? '不填写则不修改' : '登录密码'"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.show = false">取 消</el-button>
        <el-button type="primary" v-loading="dialog.loading" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="discountDialog.title" :visible="discountDialog.show"width="80%">
      <div>
        <discount ref="discount" :user-id="discountDialog.id"></discount>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="discountDialog.show = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {request} from '../libs/base'
import sha1 from 'js-sha1'
import discount from './discount.vue'
import {Message} from 'element-ui'

export default {
  components: {
    discount
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('线路名称不能为空'));
      }
      request('line/check_name_exists', {'name': value}).then(res => {
        if (res.data) {
          callback(new Error('线路名称已存在'))
        } else {
          callback()
        }
      })
    }
    const validatePass = (rule, value, callback) => {
      if (this.info.id == 0 && value === '') {
        callback(new Error('密码不能为空'))
      } else if (value) {
        let ver = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/
        if (!ver.test(value)) {
          callback(new Error('必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-16之间！'))
        }
      }
      callback()
    }
    return {
      discountDialog: {
        loading: false,
        show: false,
        title: '',
        id: 0
      },
      dialog: {
        loading: false,
        show: false,
        title: '',
        id: 0
      },
      loading: false,
      page: {
        page: 1,
        size: 15,
        total: 0
      },
      list: [],
      info: {},
      rules: {
        name: {validator: validateName, trigger: 'blur'},
        password: {validator: validatePass, trigger: 'blur'}
      }
    }
  },
  methods: {
    getList() {
      let param = {
        page: this.page.page,
        role: 1
      }
      this.loading = true
      request('user/list', param).then(res => {
        res = res.data
        this.page.size = res.per_page
        this.page.total = res.total
        this.list = res.data
        this.loading = false
      })
    },
    pageChange(page) {
      this.page.page = page
      this.getList()
    },
    showDiscountDialog(item) {
      this.discountDialog.show = true
      this.discountDialog.title = item.name
      this.discountDialog.id = item.id
    },
    initDiscountList() {
      this.$refs.discount.render(this.discountDialog.id)
    },
    add() {
      this.info = {
        id: 0,
        username: '',
        password: ''
      }
      this.dialog.title = '添加用户'
      this.dialog.show = true
    },
    edit(item) {
      this.info = item
      this.info.password = ''
      this.dialog.title = '编辑用户:' + item.username
      this.dialog.show = true
    },
    save() {
      this.$refs.form.validate((valid) => {
        let data = {
          username: this.info.username
        }
        if (valid) {
          if (this.info.password != '') {
            data.password = sha1(this.info.password)
          }
          this.dialog.loading = true
          request('user/save', data).then(res => {
            Message.success({
              message: '保存成功！'
            })
            this.dialog.show = false
            this.dialog.loading = false
            if (this.info.id === 0) {
              this.getList()
            }
          }).catch(e => {
            this.dialog.loading = false
          })
        }
      })
    },
    del(index, item) {
      this.$confirm('确认要删除用户:' + item.username, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request('user/del', {id: item.id}).then(res => {
          Message.success({
            message: '删除成功！'
          })
          this.list.splice(index, 1)
          this.page.total -= 1
        })
      })
    }
  },
  mounted() {
    this.getList()
  }
}
</script>
